<template>
  <div>
    <el-card class="box-card">
      <div style="display: flex; justify-content: space-between; align-items: center;">
        <h2>填写零件属性：<span style="font-size: 14px; color: #999;">(除规格外其他属性不能为空)</span></h2>
        <el-button type="danger" round @click="resetForm">清空属性</el-button>
      </div>
      <el-form 
      ref="lingjianForm"
      :inline="true" 
      :model="lingjian" 
      :rules="rules" 
      class="custom-form">
        <el-form-item
            v-for="(item,index) in lingjianItems"
            :key="item.id"
            :label="item.label"
            :label-width="item.labelWidth"
            :prop="item.model.split('.')[1]"

        >
          <el-input
              v-if="item.model !== 'lingjian.leibie'"
              v-model="lingjian[item.model.split('.')[1]]"
              :placeholder=item.label
          ></el-input>

          <el-select
              v-else
              v-model="lingjian.leibie"
              :placeholder=item.label
          >
            <el-option
                v-for="option in leibieOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="box-card">
      <div style="text-align: center;">
        <el-button type="primary" plain @click="generateCode">👆生成编码👇</el-button>
        <el-button type="success" plain @click="parseAttributes">👇解析属性👆</el-button>
      </div>
    </el-card>

    <el-card class="box-card">
      <!-- <h2>14位编码：</h2>
      <div v-if="generatedCode" style="font-size: 24px; font-weight: bold; text-align: center; padding: 20px 0;">
        {{ generatedCode }}
      </div> -->
      <el-input
        v-model="generatedCode"
        placeholder="14位编码"
      ></el-input>
      <!-- <div v-else style="color: #999; text-align: center; padding: 20px 0;">
        请补充零件属性后再点击"开始生成"
      </div> -->
    </el-card>
  </div>
</template>

<script>
export default {
  name: "Autocode",
  data() {
    return {
      lingjian: {
        tuhao: '', //图号
        name: '', //名称
        guige: '', //规格
        cailiao: '',//材料
        leibie: '', //类别
      },
      lingjianItems: [
        { id: 1, label: '图号:', model: 'lingjian.tuhao', labelWidth: '100px' },
        { id: 2, label: '名称:', model: 'lingjian.name', labelWidth: '100px' },
        { id: 3, label: '规格:', model: 'lingjian.guige', labelWidth: '100px' },
        { id: 4, label: '材料:', model: 'lingjian.cailiao', labelWidth: '100px' },
        { id: 5, label: '类别:', model: 'lingjian.leibie', labelWidth: '100px' },
      ],
      leibieOptions: [
        { value: '标准件', label: '标准件' },
        { value: '机加件', label: '机加件' },
        { value: '钣金件', label: '钣金件' },
        { value: '组件', label: '组件' },
        { value: '机加/钣金件', label: '机加/钣金件' }
      ],
      generatedCode: '', // 存储生成的14位编码
      rules: {
        tuhao: [{ required: true, message: '请输入图号', trigger: 'blur' }],
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        // guige: [{ required: true, message: '请输入规格', trigger: 'blur' }],
        // cailiao: [{ required: true, message: '请输入材料', trigger: 'blur' }],
        leibie: [{ required: true, message: '请选择类别', trigger: 'change' }]
      }
    };
  },
  mounted() {
    // 页面加载时
    // this.clearCount();
  },
  computed: {

  },
  watch: {

  },
  methods: {
    generateCode() {
      // 创建表单引用
      this.$refs.lingjianForm.validate(valid => {
        if (valid) {
          // 表单验证通过，调用接口
          this.$request.post('/autocode/autocode/', this.lingjian)
            .then(res => {
              if (res.code === '200') {
                this.generatedCode = res.data; // 假设接口返回的就是编码
                this.$message.success('编码生成成功');
              } else {
                this.$message.error(res.message || '生成编码失败');
              }
            })
            .catch(error => {
              this.$message.error('请求失败: ' + error.message);
            });
        } else {
          this.$message.error('请填写完整的零件属性信息');
          return false;
        }
      });

      // 这里简单模拟生成14位编码，实际应根据业务规则生成
      // const randomCode = Math.floor(Math.random() * 100000000000000).toString().padStart(14, '0');
      // this.generatedCode = randomCode;
      
      // 实际应用中，这里应该调用后端API生成编码
      // this.$axios.post('/api/generateCode', this.lingjian)
      //   .then(response => {
      //     this.generatedCode = response.data.code;
      //   })
      //   .catch(error => {
      //     this.$message.error('生成编码失败: ' + error.message);
      //   });
    },
    parseAttributes(){
      if (!this.generatedCode) {
        this.$message.warning('请先填写编码再解析属性');
        return;
      }
      this.$request.post('/autocode/parseAttributes/', this.generatedCode)
        .then(res => {
          if (res.code === '200') {
            const { tuhao, name, guige, cailiao, leibie } = res.data;
            this.lingjian = { tuhao, name, guige, cailiao, leibie };
            this.$message.success('属性解析成功');
          } else {
            this.$message.error(res.message || '解析属性失败');
          }
        })
        .catch(error => {
          this.$message.error('请求失败: ' + error.message);
        });
    },
    clearCount() {
      this.$request.get('/autocode/clearCount').then(res => {
        if (res.code === '200') {
          this.$message.success(res.data || '连接服务并清除缓存成功');
        } else {
          this.$message.error(res.message || '缓存清除失败');
        }
      })
      .catch(error => {
        this.$message.error('请求失败: ' + error.message);
      });
    },
    resetForm() {
      this.lingjian = {
        tuhao: '',
        name: '',
        guige: '',
        cailiao: '',
        leibie: ''
      };
      this.generatedCode = '';
      // this.$message.success('表单已清空');
    }
  },
}
</script>

<style scoped>
.box-card {
  margin: 10px;
  max-height: calc(100vh - 20px); /* 限制高度，确保不会超出视窗 */
  overflow-y: auto; /* 添加垂直滚动条 */
}
</style>